// main.js

document.addEventListener('DOMContentLoaded', function () {
    // 注册页面逻辑
    const signupForm = document.getElementById('signup-form');
    if (signupForm) {
        signupForm.addEventListener('submit', function (event) {
            event.preventDefault();
            const username = document.getElementById('inputUsername').value;
            const email = document.getElementById('inputEmail').value;
            const password = document.getElementById('inputPassword').value;
            const confirmPassword = document.getElementById('inputConfirmPassword').value;

            if (password !== confirmPassword) {
                alert('The password does not match the confirmation password');
                return;
            }

            const user = {
                username: username,
                email: email,
                password: password,
                profile: {
                    age: null,
                    gender: null
                },
                diningExperiences: []
            };

            localStorage.setItem('user', JSON.stringify(user));
            alert('Your registration was successful !');
            window.location.href = 'login.html';
        });
    }

    // 登录页面逻辑
    const loginForm = document.getElementById('login-form');
    if (loginForm) {
        loginForm.addEventListener('submit', function (event) {
            event.preventDefault();
            const email = document.getElementById('inputEmail').value;
            const password = document.getElementById('inputPassword').value;

            const storedUser = JSON.parse(localStorage.getItem('user'));
            if (storedUser && storedUser.email === email && storedUser.password === password) {
                localStorage.setItem('isLoggedIn', 'true');
                alert('login successfully！');
                window.location.href = 'user.html';
            } else {
                alert('The email address or password is incorrect');
            }
        });
    }

    // 用户页面逻辑
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    if (isLoggedIn) {
        const storedUser = JSON.parse(localStorage.getItem('user'));

        // 更新用户信息
        document.getElementById('username').textContent = storedUser.username;
        document.getElementById('email').textContent = storedUser.email;
        document.getElementById('age').textContent = storedUser.profile.age || 'null';
        document.getElementById('gender').textContent = storedUser.profile.gender || 'null';

        // 编辑用户信息
        const editUserInfoForm = document.getElementById('editUserInfoForm');
        if (editUserInfoForm) {
            editUserInfoForm.addEventListener('submit', function (event) {
                event.preventDefault();
                storedUser.username = document.getElementById('inputNewUsername').value;
                storedUser.email = document.getElementById('inputNewEmail').value;
                storedUser.profile.age = document.getElementById('inputNewAge').value;
                storedUser.profile.gender = document.getElementById('inputNewGender').value;

                localStorage.setItem('user', JSON.stringify(storedUser));
                alert('User information has been updated！');
                window.location.reload();
            });
        }

        // 添加就餐经历
        const addDiningExperienceForm = document.getElementById('addDiningExperienceForm');
        if (addDiningExperienceForm) {
            addDiningExperienceForm.addEventListener('submit', function (event) {
                event.preventDefault();
                const date = document.getElementById('inputDate').value;
                const restaurant = document.getElementById('inputRestaurant').value;
                const rating = document.getElementById('inputRating').value;
                const review = document.getElementById('inputReview').value;

                const newExperience = {
                    date: date,
                    restaurant: restaurant,
                    rating: rating,
                    review: review
                };

                storedUser.diningExperiences.push(newExperience);
                localStorage.setItem('user', JSON.stringify(storedUser));
                alert('Card added！');
                window.location.reload();
            });
        }

        // 显示就餐经历
        const diningExperiencesContainer = document.getElementById('dining-experiences');
        if (diningExperiencesContainer) {
            storedUser.diningExperiences.forEach((exp, index) => {
                const card = document.createElement('div');
                card.className = 'card';
                card.innerHTML = `
                    <div class="card-body">
                        <h5 class="card-title">${exp.restaurant}</h5>
                        <h6 class="card-subtitle mb-2 text-muted">${exp.date}</h6>
                        <p class="card-text">Rating: ${exp.rating}</p>
                        <p class="card-text">${exp.review}</p>
                        <button class="btn btn-warning btn-edit" data-index="${index}">Edit</button>
                        <button class="btn btn-danger btn-delete" data-index="${index}">Delete</button>
                    </div>
                `;
                diningExperiencesContainer.appendChild(card);
            });

            // 处理删除和修改按钮点击事件
            document.querySelectorAll('.btn-delete').forEach(button => {
                button.addEventListener('click', function () {
                    const index = this.getAttribute('data-index');
                    storedUser.diningExperiences.splice(index, 1);
                    localStorage.setItem('user', JSON.stringify(storedUser));
                    alert('Card deleted！');
                    window.location.reload();
                });
            });

            document.querySelectorAll('.btn-edit').forEach(button => {
                button.addEventListener('click', function () {
                    const index = this.getAttribute('data-index');
                    const experience = storedUser.diningExperiences[index];
                    document.getElementById('inputDate').value = experience.date;
                    document.getElementById('inputRestaurant').value = experience.restaurant;
                    document.getElementById('inputRating').value = experience.rating;
                    document.getElementById('inputReview').value = experience.review;

                    const saveBtn = document.querySelector('#addDiningExperienceForm button[type="submit"]');
                    saveBtn.textContent = 'Save Changes';
                    saveBtn.onclick = function (event) {
                        event.preventDefault();
                        storedUser.diningExperiences[index] = {
                            date: document.getElementById('inputDate').value,
                            restaurant: document.getElementById('inputRestaurant').value,
                            rating: document.getElementById('inputRating').value,
                            review: document.getElementById('inputReview').value
                        };
                        localStorage.setItem('user', JSON.stringify(storedUser));
                        alert('card updated！');
                        window.location.reload();
                    };

                    const addModal = new bootstrap.Modal(document.getElementById('addDiningExperienceModal'));
                    addModal.show();
                });
            });
        }

        // 登出逻辑
        const logoutBtn = document.getElementById('logoutBtn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', function () {
                localStorage.setItem('isLoggedIn', 'false');
                alert('logout');
                window.location.href = 'login.html';
            });
        }
    } else {
        // 如果没有登录，重定向到登录页面
        if (window.location.pathname.includes('user.html')) {
            alert('Please log in first');
            window.location.href = 'login.html';
        }
    }
});

// main.js

document.addEventListener('DOMContentLoaded', function () {
    const restaurantList = document.getElementById('restaurant-list');

    // 初始化餐厅列表
    let restaurants = JSON.parse(localStorage.getItem('restaurants')) || [];

    // 渲染餐厅列表
    function renderRestaurants() {
        restaurantList.innerHTML = '';
        restaurants.forEach((restaurant, index) => {
            const card = document.createElement('div');
            card.className = 'card';
            card.innerHTML = `
                <div class="card-body">
                    <h5 class="card-title">${restaurant.name}</h5>
                    <p class="card-text">Address: ${restaurant.address}</p>
                    <img src="${restaurant.imageUrl}" class="card-img-top" alt="${restaurant.name}">
                    <p class="card-text">Average Cost: $${restaurant.averageCost}</p>
                    <p class="card-text">User Rating: ${restaurant.userRating}</p>
                    <button class="btn btn-warning btn-edit" data-index="${index}">Edit</button>
                    <button class="btn btn-danger btn-delete" data-index="${index}">Delete</button>
                </div>
            `;
            restaurantList.appendChild(card);
        });
    }

    // 添加餐厅
    const addRestaurantForm = document.getElementById('addRestaurantForm');
    if (addRestaurantForm) {
        addRestaurantForm.addEventListener('submit', function (event) {
            event.preventDefault();
            const restaurant = {
                name: document.getElementById('inputRestaurantName').value,
                address: document.getElementById('inputAddress').value,
                imageUrl: document.getElementById('inputImageUrl').value,
                averageCost: document.getElementById('inputAverageCost').value,
                userRating: document.getElementById('inputUserRating').value
            };

            restaurants.push(restaurant);
            localStorage.setItem('restaurants', JSON.stringify(restaurants));
            alert('Restaurant added！');
            renderRestaurants();
            addRestaurantForm.reset();
            const addModal = new bootstrap.Modal(document.getElementById('addRestaurantModal'));
            addModal.hide();
        });
    }

    // 编辑餐厅
    restaurantList.addEventListener('click', function (event) {
        if (event.target.classList.contains('btn-edit')) {
            const index = event.target.getAttribute('data-index');
            const restaurant = restaurants[index];

            document.getElementById('inputRestaurantName').value = restaurant.name;
            document.getElementById('inputAddress').value = restaurant.address;
            document.getElementById('inputImageUrl').value = restaurant.imageUrl;
            document.getElementById('inputAverageCost').value = restaurant.averageCost;
            document.getElementById('inputUserRating').value = restaurant.userRating;

            const saveBtn = document.querySelector('#addRestaurantForm button[type="submit"]');
            saveBtn.textContent = 'Save Changes';
            saveBtn.onclick = function (event) {
                event.preventDefault();
                restaurants[index] = {
                    name: document.getElementById('inputRestaurantName').value,
                    address: document.getElementById('inputAddress').value,
                    imageUrl: document.getElementById('inputImageUrl').value,
                    averageCost: document.getElementById('inputAverageCost').value,
                    userRating: document.getElementById('inputUserRating').value
                };
                localStorage.setItem('restaurants', JSON.stringify(restaurants));
                alert('Restaurant updated！');
                renderRestaurants();
                saveBtn.textContent = 'Submit';
                saveBtn.onclick = null;
                addRestaurantForm.reset();
                const addModal = new bootstrap.Modal(document.getElementById('addRestaurantModal'));
                addModal.hide();
            };

            const addModal = new bootstrap.Modal(document.getElementById('addRestaurantModal'));
            addModal.show();
        }
    });

    // 删除餐厅
    restaurantList.addEventListener('click', function (event) {
        if (event.target.classList.contains('btn-delete')) {
            const index = event.target.getAttribute('data-index');
            if (confirm('Are you sure you want to delete this restaurant？')) {
                restaurants.splice(index, 1);
                localStorage.setItem('restaurants', JSON.stringify(restaurants));
                alert('Restaurant deleted！');
                renderRestaurants();
            }
        }
    });

    // 初始化页面
    renderRestaurants();
});

